package com.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mapper.GoodsMapper;
import com.pojo.entity.Goods;
import com.pojo.vo.GoodsVo;
import com.service.IGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : 杨世博
 * @date: Created in 2:15 2023/6/3
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public IPage<GoodsVo> searchGoods(String goodsKey, Integer pageNum, Integer size) {
        IPage<GoodsVo> page = new Page<>();
        List<Goods> goods = new ArrayList<>();
        if (goodsKey==null || "undefined".equals(goodsKey)){
            goods = goodsMapper.selectAll();
        }else {
            goods = goodsMapper.selectGoods(goodsKey, (pageNum-1) * size, size);
        }

        List<GoodsVo> goodsVos = new ArrayList<>();
        for (Goods good : goods) {
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(good,goodsVo);
            goodsVos.add(goodsVo);
        }

        page.setSize(size);
        page.setPages(pageNum);
        page.setRecords(goodsVos);

        Integer count = goodsMapper.selectCountByName(goodsKey,goodsKey);

        page.setSize(count);

        return page;
    }

    @Override
    public Goods goodsDetail(Integer id) {
        return goodsMapper.selectById(id);
    }

    @Override
    public List<GoodsVo> recommendGoods() {
        List<Goods> goods = goodsMapper.selectAll();
        List<GoodsVo> goodsVos = new ArrayList<>();
        for (Goods good : goods) {
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(good,goodsVo);
            goodsVos.add(goodsVo);
        }
        return goodsVos;
    }
}
